package com.fruit.controller.app.user;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.apache.shiro.crypto.hash.SimpleHash;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import com.alibaba.druid.util.StringUtils;
import com.fruit.controller.base.BaseController;
import com.fruit.pojo.farmwork.BaseOperationPerson;
import com.fruit.pojo.role.SysRole;
import com.fruit.pojo.user.SysUser;
import com.fruit.pojo.user.SysWapMenu;
import com.fruit.service.farmwork.BaseOperationManager;
import com.fruit.service.user.SysRoleManager;
import com.fruit.service.user.SysUserManager;
import com.fruit.util.ResultInfo;
import com.fruit.util.ResultUtil;

@Controller
@RequestMapping(value = "/app/user")
public class UserController extends BaseController {

	@Autowired
	private SysRoleManager sysRoleService;
	
	@Autowired
	private SysUserManager sysUserService;
	
	@Autowired
	private BaseOperationManager baseOperationService;
	
	@Value("${IMAGE_BASE_URL}")
	private String IMAGE_BASE_URL;
	
	
	@RequestMapping(value = "/userCenter", method = { RequestMethod.GET, RequestMethod.POST })
	@ResponseBody
	public Map<String, Object> userinfo(String userId){
		Map<String, Object> resMap = new HashMap<String, Object>();
		try{	
			SysUser sysUser = new SysUser();
			sysUser.setUserId(userId);
			sysUser = sysUserService.getUserInfo(sysUser);
			if(sysUser==null){
				resMap.put("result", this.initResult(ResultInfo.ERROR, "ERROR", "用户不存在!"));
				return resMap;
			}
			SysRole sr = sysRoleService.getRoleInfo(sysUser.getRoleId());
			if(sr != null){
				sysUser.setRoleName(sr.getRoleName());
			}
			resMap.put("sysUser", sysUser);
			resMap.put("result", this.initResult(ResultInfo.SUCCESS, "ok", "成功"));
			return resMap;
		}catch(Exception e){
			e.printStackTrace();
			resMap.put("result", ResultUtil.initResult(ResultInfo.ERROR, "exception", "系统异常!"));
			return resMap;
		}
	}
	
	@RequestMapping(value = "/index", method = { RequestMethod.GET, RequestMethod.POST })
	@ResponseBody
	public Map<String, Object> init(String userId){
		Map<String, Object> resMap = new HashMap<String, Object>();
		try{	
			SysUser sysUser = new SysUser();
			sysUser.setUserId(userId);
			sysUser = sysUserService.getUserInfo(sysUser);
			List<SysWapMenu> wapMenu = sysRoleService.getUserWapMenu(sysUser.getRoleId());				
			if(wapMenu != null && wapMenu.size() > 0){
				for(SysWapMenu swm:wapMenu){
					if("01".equals(swm.getMenuType())){
						if("01".equals(swm.getMenuCode())){
							int farmNum = baseOperationService.countRecords(userId);
							swm.setHandelNum(""+farmNum);
							swm.setHandelType("01");
						}else {
							swm.setHandelNum("0");
							swm.setHandelType("00");
						}
					}
				}
			}
			resMap.put("wapMenu", wapMenu);
			resMap.put("result", this.initResult(ResultInfo.SUCCESS, "ok", "成功"));
			return resMap;
		}catch(Exception e){
			e.printStackTrace();
			resMap.put("result", ResultUtil.initResult(ResultInfo.ERROR, "exception", "系统异常!"));
			return resMap;
		}
		
	}
	
	@RequestMapping(value = "getUserToken", method = { RequestMethod.GET, RequestMethod.POST })
	@ResponseBody
	public Map<String, Object> getUserToken(HttpServletRequest request,HttpServletResponse response, HttpSession session, String userId){
		this.logBefore(logger, "获取UserToken");
		Map<String, Object> resMap = new HashMap<String, Object>();
		try{
		SysUser sysUser = new SysUser();
		sysUser.setUserId(userId);
		sysUser = sysUserService.getUserInfo(sysUser);
		session.removeAttribute("sysUser");
		session.setAttribute("sysUser", sysUser);
		resMap.put("result", this.initResult(ResultInfo.SUCCESS, "ok", "成功"));
		resMap.put("sessionId", session.getId());
		}catch(Exception e){
			e.printStackTrace();
			this.logError(logger, e.getMessage());
			resMap.put("result", this.initResult(ResultInfo.ERROR, "exception", "系统繁忙!"));
		}
		this.logAfter(logger);
		return resMap;
	}		
	
	public static void main(String[] args) {
		String passwd = new SimpleHash("SHA-1", "123456", "123456").toString(); // 密码加密
		System.out.println(passwd);
	}
	
	@RequestMapping(value = "updatePwd", method = { RequestMethod.GET, RequestMethod.POST })
	@ResponseBody
	public Map<String, Object> updatePwd(String userId,String oldPwd,String newPwd){
		this.logBefore(logger, "修改密码");
		Map<String, Object> resMap = new HashMap<String, Object>();
		try{
			if(StringUtils.isEmpty(newPwd) && StringUtils.isEmpty(userId) && StringUtils.isEmpty(oldPwd)){
				resMap.put("result", ResultUtil.initResult(ResultInfo.ERROR, "ERROR", "参数错误!"));
				return resMap;
			}
			SysUser sysUser = new SysUser();
			sysUser.setUserId(userId);
			sysUser = sysUserService.getUserInfo(sysUser);
			if(sysUser == null){
				resMap.put("result", ResultUtil.initResult(ResultInfo.ERROR, "ERROR", "用户不存在!"));
				return resMap;
			}
			String op = new SimpleHash("SHA-1", sysUser.getUserName(), oldPwd).toString();
			if(!op.equals(sysUser.getPassword())){
				resMap.put("result", ResultUtil.initResult(ResultInfo.ERROR, "ERROR", "旧密码输入有误!"));
				return resMap;
			}
			String np = new SimpleHash("SHA-1", sysUser.getUserName(), newPwd).toString();
			SysUser su = new SysUser();
			su.setUserId(userId);
			su.setPassword(np);
			int num = sysUserService.updateUserPwd(su);
			if(num==1){
				resMap.put("result", ResultUtil.initResult(ResultInfo.SUCCESS, "SUCCESS", "修改成功!"));
			} else {
				resMap.put("result", ResultUtil.initResult(ResultInfo.ERROR, "ERROR", "修改失败!"));
			}
		}catch(Exception e){
			e.printStackTrace();
			this.logError(logger, e.getMessage());
			resMap.put("result", this.initResult(ResultInfo.ERROR, "exception", "网络繁忙!"));
		}
		this.logAfter(logger);
		return resMap;
	}
	
}
